package com.topisv.tms.service.stock.outstorage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.hibernate.ejb.criteria.predicate.ComparisonPredicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.dto.CommonDto;
import com.topisv.tms.entity.edb.EdbInOutStore;
import com.topisv.tms.entity.edb.EdbTask;
import com.topisv.tms.entity.interfacetask.InterfaceTaskEnum;
import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.entity.stock.oustorage.OutstorageBill;
import com.topisv.tms.entity.stock.oustorage.OutstorageBillItem;
import com.topisv.tms.entity.stock.oustorage.OutstoragePickTask;
import com.topisv.tms.entity.stock.reverse.ReverseBill;
import com.topisv.tms.entity.stock.reverse.ReverseBillItem;
import com.topisv.tms.repository.AreaGroupDao;
import com.topisv.tms.repository.CustomersDao;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.repository.UserDao;
import com.topisv.tms.repository.edb.EdbInOutStoreDao;
import com.topisv.tms.repository.edb.EdbTaskDao;
import com.topisv.tms.repository.stock.CusStockDao;
import com.topisv.tms.repository.stock.outstorage.OutstorageBillDao;
import com.topisv.tms.repository.stock.outstorage.OutstorageBillItemDao;
import com.topisv.tms.repository.stock.outstorage.OutstoragePickTaskDao;
import com.topisv.tms.repository.stock.reverse.ReverseBillDao;
import com.topisv.tms.repository.stock.reverse.ReverseBillItemDao;
import com.topisv.tms.repository.task.interfacetask.InterfaceTaskDao;
import com.topisv.tms.rest.qimen.qmservice.DeliveryOrderConfirmService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.base.BaseService;
import com.topisv.tms.service.edb.EdbInOutStoreService;
import com.topisv.tms.utils.rule.TMSTransportRule;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 出库单_service
 * @author ch
 *
 */
@Component
@Transactional(readOnly = true)
public class OutstorageBillService extends BaseService{
	
	@Autowired
	private OutstorageBillDao outstorageBillDao;
	@Autowired
	private CusStockDao cusStockDao;
	@Autowired
	private OutstorageBillItemDao outstorageBillItemDao;
	@Autowired
	private OutstoragePickTaskDao outstoragePickTaskDao;
	@Autowired
	private CustomersDao customersDao;
	@Autowired
	private AreaGroupDao areaGroupDao;
	@Autowired
	private EdbInOutStoreService edbInOutStoreService;
	@Autowired
	private ReverseBillDao reverseBillDao;
	@Autowired
	private ReverseBillItemDao reverseBillItemDao;
	@Autowired
	private EdbInOutStoreDao edbInOutStoreDao;
	@Autowired
	private EdbTaskDao edbTaskDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private DeliveryOrderConfirmService deliveryOrderConfirmService;
	@Autowired
	private EdiOrderDao ediOrderDao;
	@Autowired
	private InterfaceTaskDao interfaceTaskDao;

	/**
	 * 创建出库单
	 * @param customerCode 商家编码
	 * @param warehouseCode_out 出库仓库
	 * @param warehouseCode_in 调拨：收货仓库 ；  销售：目的地 ；    返仓：商家仓库
	 * @param infoMap 出库信息
	 * @param billType 出库类型
	 * @return
	 * @throws Exception 
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public String createBill(String customerCode,String warehouseCode_out, String warehouseCode_in,Map<String, Integer> infoMap,String billType) throws Exception {
		return createBill(customerCode,warehouseCode_out,warehouseCode_in,null,infoMap,billType,null);
	}
	/**
	 * 创建出库单
	 * @param customerCode 商家编码
	 * @param warehouseCode_out 出库仓库
	 * @param warehouseCode_in 调拨：收货仓库 ；  销售：目的地 ；    返仓：商家仓库
	 * @param infoMap 出库信息
	 * @param billType 出库类型
	 * @return
	 * @throws Exception 
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public String createBill(String customerCode,String warehouseCode_out, String warehouseCode_in,String aboutCode,Map<String, Integer> infoMap,String billType,StringBuffer billNo) throws Exception {
			List<CommonDto> pickInfoList=new ArrayList<CommonDto>();
			String errorList="";
			int goodsNum=0;
			int skuCount=0;
			boolean badGoodFlag =false;
			if("bad_return".equals(billType))badGoodFlag=true;
			for(String sku:infoMap.keySet()){
				
				int sku_num = infoMap.get(sku); // 每个sku需求数量
				goodsNum+=sku_num; //商品数量合计
				skuCount++; //sku数量合计
				List<CusStock> stockList = this.cusStockDao.loadStock(warehouseCode_out, customerCode, sku);
				
				if(!badGoodFlag){
					// 排序：库存数量升序排列，
					Collections.sort(stockList, new Comparator<CusStock>() {
						public int compare(CusStock o1, CusStock o2) {
							return o1.getSalesNum().compareTo(o2.getSalesNum());
						}
					});
				} else {
					// 排序：库存数量升序排列，
					Collections.sort(stockList, new Comparator<CusStock>() {
						public int compare(CusStock o1, CusStock o2) {
							return o1.getUnusedNum().compareTo(o2.getUnusedNum());
						}
					});
				}
				
				boolean flag = false;
				// 找到最接近满足的箱位
				for (CusStock cusStock : stockList) {
					int num =badGoodFlag?cusStock.getUnusedNum():cusStock.getSalesNum();
					if ( num >= sku_num) { 
						CommonDto dto=new CommonDto();
						dto.setField1(sku);
						dto.setField2(cusStock.getStockCode());
						dto.setField3(cusStock.getBoxCode());
						dto.setField4(sku_num);
						pickInfoList.add(dto);
						sku_num=0;
						flag = true;
						break;
					}
				}
				
				// 如果没有找到最接近的箱位，箱位组合分配。
				if (!flag) {
					Collections.reverse(stockList); // 排序，商品数量降序
					for (CusStock cusStock : stockList) {
						
						if (sku_num == 0){
							break;
						}
						
						int salesNum=badGoodFlag?cusStock.getUnusedNum():cusStock.getSalesNum();
						if(salesNum<=sku_num){
							sku_num=sku_num-salesNum;
							CommonDto dto=new CommonDto();
							dto.setField1(sku);
							dto.setField2(cusStock.getStockCode());
							dto.setField3(cusStock.getBoxCode());
							dto.setField4(salesNum);
							pickInfoList.add(dto);
							
						}else if(salesNum>sku_num){
							CommonDto dto=new CommonDto();
							dto.setField1(sku);
							dto.setField2(cusStock.getStockCode());
							dto.setField3(cusStock.getBoxCode());
							dto.setField4(sku_num);
							pickInfoList.add(dto);
							sku_num=0;
						}
						
					}
					
				}
				
				if(sku_num>0){
					if(errorList.length()>0){
						errorList+=",";
					}
					errorList+=sku;
				}
			}
			
			//如果有商品不能满足库存，返回
			if(errorList.length()>0){
				return errorList;
			}
			
			//创建出库单
			OutstorageBill bill=new OutstorageBill();
			Date now=new Date();
			bill.setAboutCode(aboutCode);
			bill.setBillCode(TMSTransportRule.generateOutstorageBillCode());
			if(billNo!=null)billNo.append(bill.getBillCode());
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			bill.setCreaterUuid(curUser==null?"ADMIN":curUser.jobuuid);
			bill.setCreateTime(now);
			bill.setCustomerCode(customerCode);
			bill.setGoodsNum(goodsNum);
			bill.setSkuNum(skuCount);
			bill.setStatus("1"); //状态 （1.创建出库单 2.领取拣货任务 3. 拣货完成 4.出库 5.收货确认 )
			bill.setWarehouseOutCode(warehouseCode_out);
			bill.setBillType(billType);
			
			if("allot".equals(billType)){
				
			}else if("sale".equals(billType)){
				warehouseCode_in="";
			}else if("return".equals(billType)){
				warehouseCode_in=customerCode;
			} else if("bad_return".equals(billType)){
				warehouseCode_in=customerCode;
			}
			bill.setWarehouseInCode(warehouseCode_in);
			
			this.outstorageBillDao.save(bill);
			
			//修改库存信息、创建出库明细
			for (CommonDto dto : pickInfoList) {
				String sku=(String) dto.getField1();
				String stockCode=(String) dto.getField2();
				String boxCode=(String) dto.getField3();
				Integer num=(Integer) dto.getField4();
				
				//修改库存信息
				CusStock stock=this.cusStockDao.loadStock(customerCode, warehouseCode_out, stockCode, boxCode, sku);
				if(!badGoodFlag){
					stock.setSalesNum(stock.getSalesNum()-num);
				} else {
					stock.setUnusedNum(stock.getUnusedNum()-num);
				}
				stock.setTransportNum(stock.getTransportNum()+num);
				this.cusStockDao.save(stock);
				
				//创建出库明细
				OutstorageBillItem item=new OutstorageBillItem();
				item.setBillCode(bill.getBillCode());
				item.setCustomerCode(customerCode);
				item.setWarehouseCode(warehouseCode_out);
				item.setStockCode(stockCode);
				item.setBoxCode(boxCode);
				item.setSku(sku);
				item.setNum(num);
				this.outstorageBillItemDao.save(item);
			}
			
			//创建拣货任务
			OutstoragePickTask pickTask=new OutstoragePickTask();
			pickTask.setBillCode(bill.getBillCode());
			pickTask.setCreateTime(now);
			pickTask.setCustomerCode(bill.getCustomerCode());
			pickTask.setStatus("undo");
			pickTask.setWarehouseCode(bill.getWarehouseOutCode());
			pickTask.setTaskCode(TMSTransportRule.generatePickTaskCode());
			this.outstoragePickTaskDao.save(pickTask);
			
			return errorList;

		
	}
	
	/**
	 * 创建出库单
	 * @param customerCode 商家编码
	 * @param warehouseCode_out 出库仓库
	 * @param warehouseCode_in 调拨：收货仓库 ；  销售：目的地 ；    返仓：商家仓库
	 * @param aboutCode E店宝出库单号
	 * @param infoMap 出库信息
	 * @param billType 出库类型
	 * @return
	 * @throws Exception 
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public String createBillEdb(String customerCode,String warehouseCode_out, String warehouseCode_in,String aboutCode,Map<String, Integer> infoMap,String billType) throws Exception {
			
			List<CommonDto> pickInfoList=new ArrayList<CommonDto>();
			String errorList="";
			int goodsNum=0;
			int skuNum=0;
			
			for(String sku:infoMap.keySet()){
				
				int sku_num = infoMap.get(sku); // 每个sku需求数量
				goodsNum+=sku_num; //商品数量合计
				skuNum++; //sku数量合计
				List<CusStock> stockList = this.cusStockDao.loadStock(warehouseCode_out, customerCode, sku);
				
				
				// 排序：库存数量升序排列，
				Collections.sort(stockList, new Comparator<CusStock>() {
					public int compare(CusStock o1, CusStock o2) {
						return o1.getSalesNum().compareTo(o2.getSalesNum());
					}
				});
				
				boolean flag = false;
				// 找到最接近满足的箱位
				for (CusStock cusStock : stockList) {
					if (cusStock.getSalesNum() >= sku_num) { 
						CommonDto dto=new CommonDto();
						dto.setField1(sku);
						dto.setField2(cusStock.getStockCode());
						dto.setField3(cusStock.getBoxCode());
						dto.setField4(sku_num);
						pickInfoList.add(dto);
						sku_num=0;
						flag = true;
						break;
					}
				}
				
				// 如果没有找到最接近的箱位，箱位组合分配。
				if (!flag) {
					Collections.reverse(stockList); // 排序，商品数量降序
					for (CusStock cusStock : stockList) {
						
						if (sku_num == 0){
							break;
						}
						
						int salesNum=cusStock.getSalesNum();
						if(salesNum<=sku_num){
							sku_num=sku_num-salesNum;
							CommonDto dto=new CommonDto();
							dto.setField1(sku);
							dto.setField2(cusStock.getStockCode());
							dto.setField3(cusStock.getBoxCode());
							dto.setField4(salesNum);
							pickInfoList.add(dto);
							
						}else if(salesNum>sku_num){
							CommonDto dto=new CommonDto();
							dto.setField1(sku);
							dto.setField2(cusStock.getStockCode());
							dto.setField3(cusStock.getBoxCode());
							dto.setField4(sku_num);
							pickInfoList.add(dto);
							sku_num=0;
						}
						
					}
					
				}
				
				if(sku_num>0){
					if(errorList.length()>0){
						errorList+=",";
					}
					errorList+=sku;
				}
			}
			
			//如果有商品不能满足库存，返回
			if(errorList.length()>0){
				return errorList;
			}
			
			//创建出库单
			OutstorageBill bill=new OutstorageBill();
			Date now=new Date();
			bill.setAboutCode(aboutCode);
			bill.setBillCode(TMSTransportRule.generateOutstorageBillCode());
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			bill.setCreaterUuid(curUser.jobuuid);
			bill.setCreateTime(now);
			bill.setCustomerCode(customerCode);
			bill.setGoodsNum(goodsNum);
			bill.setSkuNum(skuNum);
			bill.setStatus("1"); //状态 （1.创建出库单 2.领取拣货任务 3. 拣货完成 4.出库 5.收货确认 )
			bill.setWarehouseOutCode(warehouseCode_out);
			bill.setBillType(billType);
			
			if("allot".equals(billType)){
				
			}else if("sale".equals(billType)){
				warehouseCode_in="";
			}else if("return".equals(billType)){
				warehouseCode_in=customerCode;
			}
			bill.setWarehouseInCode(warehouseCode_in);
			
			this.outstorageBillDao.save(bill);
			
			//修改库存信息、创建出库明细
			for (CommonDto dto : pickInfoList) {
				String sku=(String) dto.getField1();
				String stockCode=(String) dto.getField2();
				String boxCode=(String) dto.getField3();
				Integer num=(Integer) dto.getField4();
				
				//修改库存信息
				CusStock stock=this.cusStockDao.loadStock(customerCode, warehouseCode_out, stockCode, boxCode, sku);
				stock.setSalesNum(stock.getSalesNum()-num);
				stock.setTransportNum(stock.getTransportNum()+num);
				this.cusStockDao.save(stock);
				
				//创建出库明细
				OutstorageBillItem item=new OutstorageBillItem();
				item.setBillCode(bill.getBillCode());
				item.setCustomerCode(customerCode);
				item.setWarehouseCode(warehouseCode_out);
				item.setStockCode(stockCode);
				item.setBoxCode(boxCode);
				item.setSku(sku);
				item.setNum(num);
				this.outstorageBillItemDao.save(item);
			}
			
			//创建拣货任务
			OutstoragePickTask pickTask=new OutstoragePickTask();
			pickTask.setBillCode(bill.getBillCode());
			pickTask.setCreateTime(now);
			pickTask.setCustomerCode(bill.getCustomerCode());
			pickTask.setStatus("undo");
			pickTask.setWarehouseCode(bill.getWarehouseOutCode());
			pickTask.setTaskCode(TMSTransportRule.generatePickTaskCode());
			this.outstoragePickTaskDao.save(pickTask);
			
			EdbInOutStore edbInOutStore = new EdbInOutStore();
			edbInOutStore.setBillCode(bill.getBillCode());
			edbInOutStore.setCreateTime(new Date());
			edbInOutStore.setOrderType("02");
			edbInOutStore.setTid(aboutCode);
			edbInOutStore.setCustomerCode(customerCode);
			edbInOutStore.setWhcode(warehouseCode_out);
			edbInOutStore.setStatus("0");
			edbInOutStoreDao.save(edbInOutStore);
			return errorList;

		
	}
	
	public void saveCheckInOrOutEdb(EdbTask edbTask,String item) {
		log.info("E店宝盘点出库");
		JSONObject json = JSONObject.fromObject(item);
		ReverseBill reverseBill = new ReverseBill();
		reverseBill.setBillCode(TMSTransportRule.generateReverseBillCode());
		reverseBill.setBillType("check");
		reverseBill.setCreaterUuid("ADMIN");
		reverseBill.setCreateTime(new Date());
		reverseBill.setAboutCode(json.getString("out_store_tid"));
		reverseBill.setCustomerCode(edbTask.getCustomerCode());
		reverseBill.setWarehouseCode(edbTask.getWarehouseCode());
		reverseBill.setStatus("undo");
		reverseBill.setIsAllocated("N");
		reverseBillDao.save(reverseBill);
		JSONArray  outstore_tid = json.getJSONArray("outstore_tid_item");
		List<ReverseBillItem> itemList = new ArrayList<ReverseBillItem>();
		for(int i=0; i<outstore_tid.size(); i++){
			JSONObject outstore_tid_item = (JSONObject)outstore_tid.get(i);
			ReverseBillItem billItem = new ReverseBillItem();
			billItem.setBillCode(reverseBill.getBillCode());
			billItem.setCustomerCode(reverseBill.getCustomerCode());
			billItem.setOrderNumFix(0);
			billItem.setSalesNumFix(outstore_tid_item.getInt("out_store_num"));
			billItem.setUnusedNumFix(0);
			billItem.setSku(outstore_tid_item.getString("bar_code"));
			billItem.setStatus("undo");
//			billItem.setStockCode();
			
			billItem.setWarehouseCode(reverseBill.getWarehouseCode());
			itemList.add(billItem);
		}
		this.reverseBillItemDao.save(itemList);
		EdbInOutStore edbInOutStore = new EdbInOutStore();
		edbInOutStore.setBillCode(reverseBill.getBillCode());
		edbInOutStore.setCreateTime(new Date());
		edbInOutStore.setOrderType("02");
		edbInOutStore.setTid(reverseBill.getAboutCode());
		edbInOutStore.setCustomerCode(reverseBill.getCustomerCode());
		edbInOutStore.setWhcode(reverseBill.getWarehouseCode());
		edbInOutStore.setStatus("0");
		edbInOutStoreDao.save(edbInOutStore);
		log.info("E店宝盘点出库消息：end，");
	}
	
	public Page<OutstorageBill> loadPageByParam(QueryParamHolder paramHolder) {
		Page<OutstorageBill> page = findByJson(paramHolder, outstorageBillDao, OutstorageBill.class);
		if (page != null) {
			List<OutstorageBill> list = page.getContent();
			for (OutstorageBill bill : list) {
				this.setDetail(bill);
			}
		}
		return page;
	}

	/**
	 * 分页查询
	 * @param param
	 * @return
	 */
	public Page<OutstorageBill> loadPageByParam(Map<String, Object> param,int pageNumber, int pageSize) {
		Sort sort = new Sort(Sort.Direction.DESC,"id");
	    PageRequest pageRequest = new PageRequest(pageNumber-1, pageSize, sort);
	    Specification<OutstorageBill> spec =this.getWhereClause(param);
	    Page<OutstorageBill> page = this.outstorageBillDao.findAll(spec, pageRequest);
	    if(page!=null){
	    	List<OutstorageBill> list=page.getContent();
	    	for (OutstorageBill bill : list) {
				this.setDetail(bill);
			}
	    }
	    return page;
	}
	
	/**
	 * 设置属性
	 * @param bill
	 */
	private void setDetail(OutstorageBill bill) {
		
		//customer
		String customerCode=bill.getCustomerCode();
		Customers customer=this.customersDao.findByCustomerCode(customerCode);
		bill.setCustomer(customer);
		
		//warehouse
		String warehouseOutCode=bill.getWarehouseOutCode();
		AreaGroup warehouseOut=this.areaGroupDao.findByGroupCode(warehouseOutCode);
		bill.setWarehouseOut(warehouseOut);
		
		String warehouseInCode=bill.getWarehouseInCode();
		AreaGroup warehouseIn=this.areaGroupDao.findByGroupCode(warehouseInCode);
		bill.setWarehouseIn(warehouseIn);
		
		//creater
		User user=this.userDao.findByJobuuid(bill.getCreaterUuid());
		bill.setCreater(user);
		
		
		
	}

	/**
	 * 条件封装
	 * @param param
	 * @return
	 */
	private Specification<OutstorageBill> getWhereClause(final Map<String, Object> param) {
		 return new Specification<OutstorageBill>(){
		    @Override
		    public Predicate toPredicate(Root<OutstorageBill> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
		      Predicate pre = cb.conjunction();
		      
		     //customerCodes
		     String customerCodes=(String) param.get("customerCodes");
		     if(StringUtils.isNotBlank(customerCodes)) {
		    	  String[] customerCodeSplit = customerCodes.split(":");
				  ComparisonPredicate[] tempCustomerCode = new ComparisonPredicate[customerCodeSplit.length];
				  int i = 0;
				  for (String _customerCode : customerCodeSplit) {
					 tempCustomerCode[i] = (ComparisonPredicate) cb.equal(r.get("customerCode"), _customerCode);
					 i++;
				  }
				  pre.getExpressions().add(cb.or(tempCustomerCode));
		      }
		     
		     //customerCode
		     String customerCode=(String) param.get("customerCode");
		     if(StringUtils.isNotBlank(customerCode)) {
		    	 pre.getExpressions().add(cb.equal(r.<String>get("customerCode"),customerCode));
		      }
		      
		      //warehouseOutCode
		      String warehouseOutCode=(String) param.get("warehouseOutCode");
		      if(StringUtils.isNotBlank(warehouseOutCode)){
		         pre.getExpressions().add(cb.like(r.<String>get("warehouseOutCode"),warehouseOutCode));
			  }
		      
		      //warehouseInCode
		      String warehouseInCode=(String) param.get("warehouseInCode");
		      if(StringUtils.isNotBlank(warehouseInCode)){
		         pre.getExpressions().add(cb.like(r.<String>get("warehouseInCode"),warehouseInCode));
			  }
		      
		      //billType
		      String billType=(String) param.get("billType");
		      if(StringUtils.isNotBlank(billType)){
		         pre.getExpressions().add(cb.like(r.<String>get("billType"),billType));
			  }
		      
		      //billCode
		      String billCode=(String) param.get("billCode");
		      if(StringUtils.isNotBlank(billCode)){
		         pre.getExpressions().add(cb.like(r.<String>get("billCode"),"%"+billCode+"%"));
			  }
		      
		      //status
		      String status=(String) param.get("status");
		      if(StringUtils.isNotBlank(status)){
		         pre.getExpressions().add(cb.like(r.<String>get("status"),status));
			  }
		      
		      //创建时间
		      Date fromDate= (Date) param.get("fromDate");
		      if (fromDate != null) {
		        pre.getExpressions().add(cb.greaterThanOrEqualTo(r.<Date>get("createTime"), fromDate));
		      }
		      
		      Date toDate= (Date) param.get("toDate");
		      if (toDate != null) {
		        pre.getExpressions().add(cb.lessThanOrEqualTo(r.<Date>get("createTime"), toDate));
		      }
		      
		      return pre;
		    }
		  };
	}

	/**
	 * 查询出库单
	 * @param billCode
	 * @return
	 */
	public OutstorageBill loadByBillCode(String billCode) {
		return this.outstorageBillDao.loadByBillCode(billCode);
	}

	/**
	 * 保存运输信息
	 * @param driverInfo
	 * @param carInfo
	 * @param outTimeStr
	 * @param remark
	 * @param billCode
	 */
	@Transactional(readOnly = false)
	public String saveTransInfo(String driverInfo, String carInfo,String outTimeStr, String remark, String billCode) {
		try {
			
			OutstorageBill bill=this.outstorageBillDao.loadByBillCode(billCode);
			
			bill.setDriverInfo(driverInfo);
			bill.setCarInfo(carInfo);
			bill.setRemark(remark);
			bill.setOutTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(outTimeStr));
			
			this.outstorageBillDao.save(bill);
			
			return "true";
		
		} catch (Exception e) {
			return "false";
		}
	}
	
	public void sendEdb(String billCode)
	{/*
		EdbInOutStore edbInOutStore = edbInOutStoreDao.findByBillCode(billCode);
		if(null == edbInOutStore)
		{
			log.info("E店宝出入库消息为空:" + billCode);
			return;
		}
		String method = "";
		TreeMap<String, String> map = new TreeMap<String, String>();
		if("01".equals(edbInOutStore.getOrderType()))
		{
			method = "edbInStoreConfirm";
			map.put("inStorage_no", edbInOutStore.getTid());
		}
		else
		{
			method = "edbOutStoreConfirm";
			map.put("outStorage_no", edbInOutStore.getTid());
		}
		
		EdbTask edbTask = edbTaskDao.findTask(edbInOutStore.getCustomerCode(), edbInOutStore.getWhcode(), method);
		if(null == edbTask)
		{
			log.info("E店宝出入库接口消息为空");
			return;
		}
		Map<String,String> paramMap = getParam(edbTask.getParam());
		paramMap.putAll(map);;
		String result = EdbAPITool.edbInterface(edbTask, paramMap);
		JSONObject json = JSONObject.fromObject(result);
		if(json.containsKey("Success"))
		{
			edbInOutStore.setStatus("1");
			edbInOutStoreDao.save(edbInOutStore);
		}
		
	*/}
	
	public Map<String,String> getParam(String param)
	{
		TreeMap<String, String> map = new TreeMap<String, String>();
		if("".equals(param) || param == null)
		{
			return map;
		}
		String[] entrys = param.split("::");
		for(String entry : entrys)
		{
			String[] p = entry.split("#");
			map.put(p[0], p[1]);
		}
		return map;
	}

	
	public Map<String, Object> outstorageBillQMResend(String[] orderNos, String[] customerCodes) throws Exception {
	    Map<String, Object> result = new HashMap<String, Object>();
	    int sum = orderNos.length;
	    int successNum = 0;
	    int failureNum = 0;
	    int undoNum = 0;
	    for(int i = 0; i < orderNos.length; i++) {
	        String msg = deliveryOrderConfirmService.send(orderNos[i], customerCodes[i]);
            if ("success".equals(msg)) {
                // 如果成功，修改task状态为finish
                int count = interfaceTaskDao.updateStatusByRelateNoAndType(orderNos[i], InterfaceTaskEnum.STATUS_FINISH, InterfaceTaskEnum.TYPE_QM_DELIVERY_ORDER_CONFIRM);
                if (count > 0) {
                    successNum++;
                } else {
                    failureNum++;
                }
            }
            if ("failure".equals(msg)) {
                failureNum++;
            }
            if ("未接入奇门不需要发送".equals(msg)) {
                undoNum++;
            }
	    }
	    result.put("sum", sum);
	    result.put("successNum", successNum);
	    result.put("failureNum", failureNum);
	    result.put("undoNum", undoNum);
	    return result;
	}
	
}
